package com.atguigu.jucdemo.rwLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class rwLockDemo {
    private Map<String,String> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void write(String key,String value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完成");
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void read(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在读取");
            String s = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完成"+s);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        rwLockDemo rwLockDemo = new rwLockDemo();

        for (int i = 1 ; i <= 5; i++) {
            int finalI = i;
            int finalI1 = i;
            new Thread(()->{
                rwLockDemo.write(finalI+"", finalI1+"");
            },String.valueOf(i)).start();
        }

        for (int i = 1 ; i <= 5; i++) {
            int finalI = i;
            new Thread(()->{
                rwLockDemo.read(finalI+"");
            },String.valueOf(i)).start();
        }

    }
}
